<?php 

namespace Home\Controller;
use Think\Controller;

/**
* 分类区
*/
class TopicController extends Controller
{

	public function index(){
	//分类话题区
		if(!empty($_GET)){
			
			$sql = "SELECT							
						a.tname as tname,

						a.id as tid,				
						c.id as id,
						c.title as title,						
						c.time as time,
						c.content as content,
						c.views as views,
						e.head_img as img,
						e.id as uid,
						e.username as username,
						g.username as answer_user,
						g.id as answer_uid,
						g.head_img as answer_img,
						count(f.qid) as answer
					FROM
						`theme` AS a
					LEFT JOIN `question_theme` AS b ON a.id = b.tid
					LEFT JOIN `question` AS c ON b.qid = c.id
					
					LEFT JOIN `user` AS e ON c.uid = e.id
					LEFT JOIN `answer` AS f ON f.qid = c.id
					LEFT JOIN `user` AS g ON g.id = f.uid
			
					WHERE
						a.id = {$_GET['id']}
					GROUP BY
						b.qid,
						b.tid
					";


			$modle = M();
			$result1 = $modle -> query($sql);
			$sql = "SELECT							
							
						count(d.qid) as focus
						FROM
							`theme` AS a
						LEFT JOIN `question_theme` AS b ON a.id = b.tid
						LEFT JOIN `question` AS c ON b.qid = c.id					
						LEFT JOIN `question_focus` AS d ON d.qid = c.id	
						
						WHERE
							a.id = {$_GET['id']}
						GROUP BY
							b.qid
					";
			$result2 = $modle -> query($sql);

			foreach ($result1 as $k => $value) {
				$result[] = array_merge($value,$result2[$k]);
			}	

			$this->assign('result',$result);
			// var_dump($result);
			// var_dump($result);

			$this->display('Topic:topic_detail');
		}else{
			//取出话题名，话题id，话题的问题评论总数量
			$sql = "SELECT					
						a.id as id,
						a.tname as tname,						
						count(d.qid) as answer
					FROM
					`theme` AS a
					LEFT JOIN `question_theme` AS b ON a.id = b.tid
					LEFT JOIN `question` AS c ON b.qid = c.id
					LEFT JOIN `answer` AS d ON c.id = d.qid
					group by a.id
					";
			// $sql = "SELECT * FROM `theme`";
			$modle = M('theme');

			$result1 = $modle -> query($sql);
			//取出话题关注数量
			$sql = "SELECT
					count(e.uid) as focus  
					FROM
					`theme_focus` AS e
					RIGHT JOIN `theme` AS a ON e.tid = a.id
					group by a.id"
					;
			$result2 = $modle -> query($sql);

			foreach ($result1 as $k => $value) {
				$result[] = array_merge($value,$result2[$k]);
			}
			
			$this->assign('result',$result);

			$this->display();
		}
				
	}


}
?>